package com.activity;

import interfaces.NavigateToListLocate;
import interfaces.NavigateToLocateDetail;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import util.ApplicationConstant;

import com.activity.R;
import com.fragment.BookmarkRecentFragment;
import com.fragment.ListLocateFragment;
import com.fragment.LocateDetailsFragment;
import com.fragment.MainFragment;
import com.fragment.MyLocateFragment;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;

import dao.FileBookmarkRecent;
import dao.HttpPostThread;
import dao.LoadCategory;
import dao.LoadLocate;
import entities.Category;
import entities.Locate;
import entities.MyLocate;
import entities.NavigationItem;
import adapter.AdapterNavigation;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;

@SuppressLint("NewApi")
public class MainAppActivity extends FragmentActivity implements
		LocationListener, NavigateToListLocate, NavigateToLocateDetail {
	public static Typeface typeFaceFont;
	private ListView mDrawerList;// list view on navigate
	public Spinner spinnerDistance;
	// fragment manager
	MyLocateFragment myLocateFragment;
	// -----------------------------nav
	private DrawerLayout mDrawerLayout;
	private ActionBarDrawerToggle mDrawerToggle;
	private List<NavigationItem> listNavItems = new ArrayList<NavigationItem>();
	private AdapterNavigation adapterNavigation;
	// ----------------------------location
	public static LatLng orginalLatl;// toa do hien tai
	public static Geocoder geocoder;
	public static String nowAddress = "";// dia chi diem nguoi dung dang dung
	public static String unitDistance;// don vi khoang cach hien tai(km)
	public static String searchingDiaLog;
	public static String localeCode;// ma ngon ngu hien tai
	public static String TAG_FRAGMENT = "no";// flag xe xet dag ở fragment nao
	public static int distanceSelected = 1;// khoang cach mac dinh
	ArrayList<String> distanceList;// list khoang cach cho action bar locate
	public ArrayAdapter<String> adapterDistance;
	int DISTANCE[];
	// recent file store
	public static FileBookmarkRecent fileTranfer;
	// flag
	public static boolean role_spinner_selection = true;// khi set select item
														// tranh tinh trang
														// spinner chay khi set
	public ActionMode.Callback callback = new ActionMode.Callback() {

		@Override
		public boolean onPrepareActionMode(ActionMode arg0, Menu arg1) {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public void onDestroyActionMode(ActionMode arg0) {
			// TODO Auto-generated method stub
			for (Locate locate : BookmarkRecentFragment.listLocate)
				locate.setIsChecked(false);
			BookmarkRecentFragment.adaper.notifyDataSetChanged();
		}

		@Override
		public boolean onCreateActionMode(final ActionMode actionMode, Menu menu) {
			// TODO Auto-generated method stub
			getMenuInflater().inflate(R.menu.bookmark, menu);
			MenuItem item = menu.findItem(R.id.checkbox_check_all);
			CheckBox checkBoxAll = (CheckBox) item.getActionView();
			checkBoxAll
					.setOnCheckedChangeListener(new OnCheckedChangeListener() {

						@Override
						public void onCheckedChanged(CompoundButton arg0,
								boolean checked) {
							// TODO Auto-generated method stub
							if (checked) {
								for (Locate locate : BookmarkRecentFragment.listLocate)
									locate.setIsChecked(true);
							} else {
								for (Locate locate : BookmarkRecentFragment.listLocate)
									locate.setIsChecked(false);
							}
							BookmarkRecentFragment.adaper
									.notifyDataSetChanged();
							if (BookmarkRecentFragment.adaper.isEmpty())
								actionMode.finish();

						}
					});
			return true;
		}

		@Override
		public boolean onActionItemClicked(final ActionMode actionMode,
				MenuItem item) {
			// TODO Auto-generated method stub
			switch (item.getItemId()) {
			case R.id.menu_bm_delete: {
				final Handler handler = new Handler() {
					@Override
					public void handleMessage(Message msg) {
						if (BookmarkRecentFragment.listLocate.size() == 0) {
							BookmarkRecentFragment.notFoundLayout
									.setVisibility(View.VISIBLE);
							actionMode.finish();
						}
						BookmarkRecentFragment.adaper.notifyDataSetChanged();
					};
				};
				class DeleteTask extends AsyncTask<String, Integer, String> {
					@Override
					protected void onPreExecute() {
						// TODO Auto-generated method stub
						super.onPreExecute();
						// progressDialog.show();
					}

					@Override
					protected String doInBackground(String... params) {
						// TODO Auto-generated method stub
						for (int i = 0; i < BookmarkRecentFragment.listLocate
								.size(); i++) {
							Locate locate = BookmarkRecentFragment.listLocate
									.get(i);
							if (locate.getIsChecked()) {
								fileTranfer.delete(locate);
								BookmarkRecentFragment.listLocate.remove(i);
								i = -1;
							}
						}
						Log.d("Bookmark size now", "-------------------"
								+ BookmarkRecentFragment.listLocate.size());
						return null;
					}

					@Override
					protected void onPostExecute(String result) {
						// TODO Auto-generated method stub
						super.onPostExecute(result);
						// progressDialog.dismiss();
						handler.sendMessage(new Message());
					}

				}
				DeleteTask d = new DeleteTask();
				d.execute();
			}
				break;
			case R.id.menu_bm_show_on_map: {
				Intent intent = new Intent(MainAppActivity.this,
						MapActivity.class);
				intent.putExtra(ApplicationConstant.ACTION,
						ApplicationConstant.MARK_ON_MAP_SOME);
				startActivity(intent);
			}
				break;

			default:
				break;
			}
			return false;
		}
	};

	protected void onResume() {
		super.onResume();
		Log.d("--thoainguyen mainappactivity", "onresume");
		if (MapActivity.callback_detail_locate == true
				&& MapActivity.postion_locate >= 0) {
			Log.d("--thoainguyen mainappactivity callback details at postion:",
					"" + MapActivity.postion_locate);
			MapActivity.callback_detail_locate = false;
			navigateToLocateDetail(MapActivity.postion_locate);
		} else if (AddMyLocate.is_updated == true) {
			// update lai list mylocate sau khi edit hay add
			AddMyLocate.is_updated = false;
			myLocateFragment.notifyAdaper();
		}
	};

	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		localeCode = Locale.getDefault().getLanguage();
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_app_activity);
		typeFaceFont= Typeface.createFromAsset(getAssets(),
	            "fonts/Roboto-Light.ttf");
		// create file store
		fileTranfer = new FileBookmarkRecent(FileBookmarkRecent.BOOKMARK_FILE,
				getApplicationContext());

		// strict mode tranh loi khi load hinh tu url
		int SDK_INT = android.os.Build.VERSION.SDK_INT;
		if (SDK_INT > 8) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
					.permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}
		/*
		 * ----------------------------------------------------------------------
		 * ---------------------lay address hien tai
		 */
		orginalLatl = new LatLng(10.788449, 106.703612);
		geocoder = new Geocoder(getBaseContext());
		LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
		Criteria criteria = new Criteria();
		String provider = locationManager.getBestProvider(criteria, true);
		// ---------------------------------------------------------------------------------------------lay
		// vi tri hien tai
		locationManager.requestLocationUpdates(provider,
				ApplicationConstant.timeCallOnLocationChange,
				ApplicationConstant.distanceUpdateOnLocationChange, this);
		// -------------------------------------------------------------------------------------------hide
		// title and icon in actionbar
		getActionBar().setDisplayShowCustomEnabled(false);
		getActionBar().setDisplayShowTitleEnabled(false);
		// ------------------------------------------------------------------------------------------create
		// navigation
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.left_drawer);
		NavigationItem item1 = new NavigationItem(R.layout.nav_layout1);
		NavigationItem item2 = new NavigationItem(R.layout.nav_layout2);
		listNavItems.add(item1);
		listNavItems.add(item2);
		adapterNavigation = new AdapterNavigation(this, 0, listNavItems);
		mDrawerList.setAdapter(adapterNavigation);
		// enable ActionBar app icon to behave as action to toggle nav drawer
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);
		mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
		mDrawerLayout, /* DrawerLayout object */
		R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
		R.string.drawer_open, /* "open drawer" description for accessibility */
		R.string.drawer_close /* "close drawer" description for accessibility */
		) {
			public void onDrawerClosed(View view) {
				getActionBar().setTitle("mTitle");

			}

			public void onDrawerOpened(View drawerView) {
				getActionBar().setTitle("mDrawerTitle");

			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);

		if (savedInstanceState == null) {
			navigateToMainFragment();
		}
		// ------------------------------------------------------------------------------get
		// resource
		unitDistance = getResources().getString(R.string.unit);
		searchingDiaLog = getResources().getString(R.string.searching_for);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		Log.d("----MainAppActivity onPrepareOptionsMenu", "");
		mDrawerLayout.isDrawerOpen(mDrawerList);

		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		Log.d("----MainAppActivity onCreateOptionsMenu", "");
		// tao menu theo tung fragment
		if (TAG_FRAGMENT.equals("ListLocateFragment")) {
			getMenuInflater().inflate(R.menu.locate_list, menu);
			DISTANCE = new int[] {
					Integer.parseInt(getResources().getString(R.string.min_one)),
					Integer.parseInt(getResources().getString(
							R.string.min_three)),
					Integer.parseInt(getResources()
							.getString(R.string.min_five)),
					Integer.parseInt(getResources().getString(R.string.min_ten)) };
			distanceList = new ArrayList<String>();
			distanceList.add("<" + getResources().getString(R.string.min_one)
					+ " " + getResources().getString(R.string.unit));
			distanceList.add("<" + getResources().getString(R.string.min_three)
					+ " " + getResources().getString(R.string.unit));
			distanceList.add("<" + getResources().getString(R.string.min_five)
					+ " " + getResources().getString(R.string.unit));
			distanceList.add("<" + getResources().getString(R.string.min_ten)
					+ " " + getResources().getString(R.string.unit));
			adapterDistance = new ArrayAdapter<String>(getApplicationContext(),
					android.R.layout.simple_dropdown_item_1line, distanceList);
			MenuItem spinner = menu.findItem(R.id.sp_distance);
			MenuItem menuItemMark = menu.findItem(R.id.menu_show_on_map);
			spinnerDistance = (Spinner) spinner.getActionView();
			spinnerDistance.setAdapter(adapterDistance);
			spinnerDistance.post(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					// tranh tinh trang khi moi khi tao spinner goi
					// SelectedListener
					spinnerDistance
							.setOnItemSelectedListener(new OnItemSelectedListener() {

								@Override
								public void onItemSelected(AdapterView<?> arg0,
										View arg1, int pos, long arg3) {
									// TODO Auto-generated method stub
									if (role_spinner_selection == true) {
										Log.d("MainAppActivity spinner listener",
												"");
										Log.d("MainAppActivity spinner selected",
												"" + DISTANCE[pos]);
										distanceSelected = DISTANCE[pos];
										LoadLocate.listLocate.clear();
										LoadLocate loadLocate = new LoadLocate(
												DISTANCE[pos],
												ListLocateFragment.caName);
										loadLocate.execute();
									} else
										role_spinner_selection = true;
								}

								@Override
								public void onNothingSelected(
										AdapterView<?> arg0) {
									// TODO Auto-generated method stub

								}
							});
					if (distanceSelected != 1) {
						for (int i = 0; i < DISTANCE.length; i++) {
							if (DISTANCE[i] == distanceSelected) {
								Log.d("--MainAppaActivity ccc", "");
								role_spinner_selection = false;
								spinnerDistance.setSelection(i);
							}
						}
					}
				}
			});

			menuItemMark
					.setOnMenuItemClickListener(new OnMenuItemClickListener() {

						@Override
						public boolean onMenuItemClick(MenuItem item) {
							// TODO Auto-generated method stub
							// maker and move map to see all marker
							if (LoadLocate.listLocate.size() > 0) {
								Intent intent = new Intent(
										MainAppActivity.this, MapActivity.class);

								intent.putExtra(ApplicationConstant.ACTION,
										ApplicationConstant.MARK_ON_MAP_SOME);
								startActivity(intent);
							}
							return true;
						}
					});
		} else if (TAG_FRAGMENT.equals("MainFragment")) {
			getMenuInflater().inflate(R.menu.activity_main, menu);

		} else if (TAG_FRAGMENT.equals("MyLocateFragment")) {
			getMenuInflater().inflate(R.menu.my_locate, menu);
			MenuItem addnew = menu.findItem(R.id.menu_ml_add_new);
			MenuItem delAll = menu.findItem(R.id.menu_ml_delete_all);
			addnew.setOnMenuItemClickListener(new OnMenuItemClickListener() {

				@Override
				public boolean onMenuItemClick(MenuItem item) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(MainAppActivity.this,
							AddMyLocate.class);
					startActivity(intent);
					return true;
				}
			});
			delAll.setOnMenuItemClickListener(new OnMenuItemClickListener() {

				@Override
				public boolean onMenuItemClick(MenuItem item) {
					// TODO Auto-generated method stub
					if (MyLocateFragment.listMyLocates.size() > 0) {
						AlertDialog.Builder alertDialog = new AlertDialog.Builder(
								MainAppActivity.this);
						alertDialog.setMessage(getResources().getString(
								R.string.content_ask_detet_ml));
						DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								if (which == DialogInterface.BUTTON_NEGATIVE) {
								} else {
									MyLocateFragment.fileMyLocate.deleteAll();
									MyLocateFragment.notFoundLayout
											.setVisibility(View.VISIBLE);
									myLocateFragment.notifyAdaper();
								}

							}
						};
						alertDialog.setNegativeButton(
								getResources().getString(R.string.title_no),
								clickListener);
						alertDialog.setPositiveButton(
								getResources().getString(R.string.title_yes),
								clickListener);
						alertDialog.show();
					}
					return true;
				}
			});
		}
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggls
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		// gan vao toa do hien tai
		Log.d("MainAppActivity location change", "------------");
		double latitude = location.getLatitude();
		double longtitude = location.getLongitude();
		// gan vao toa do hien tai va toa do tam thoi
		orginalLatl = new LatLng(latitude, longtitude);
		// get address
		Address address;
		List<Address> list;
		if (geocoder != null) {
			try {
				list = geocoder.getFromLocation(orginalLatl.latitude,
						orginalLatl.longitude, 1);
				address = list.get(0);
				nowAddress = address.getAddressLine(0) + ", P."
						+ address.getAddressLine(1) + ", "
						+ address.getAddressLine(2);
			} catch (Exception e) {
				System.out.print(e.getMessage());
			}
		}
		Log.d("--MainAppActivity onlocation change", nowAddress);
		adapterNavigation.notifyDataSetChanged();
	}

	@Override
	public void onProviderDisabled(String arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	public void navigateToMainFragment() {
		// update the main content by replacing fragments
		mDrawerLayout.closeDrawers();
		TAG_FRAGMENT = "MainFragment";
		MainFragment fragment = new MainFragment();
		FragmentManager fragmentManager = getSupportFragmentManager();
		FragmentTransaction fragmentTransaction = fragmentManager
				.beginTransaction();
		fragmentTransaction.replace(R.id.content_frame, fragment);
		fragmentTransaction.addToBackStack(null);
		fragmentTransaction.commit();
		invalidateOptionsMenu();
		invalidateOptionsMenu();
	}

	/*
	 * flag xet hien dag fragment nao
	 */

	@Override
	public void navigateToListLocate(String caId, String caName) {
		TAG_FRAGMENT = "ListLocateFragment";
		// TODO Auto-generated method stub
		ListLocateFragment fragment = new ListLocateFragment();
		fragment.navigateToListLocate(caId, caName);
		FragmentManager fragmentManager = getSupportFragmentManager();
		FragmentTransaction fragmentTransaction = fragmentManager
				.beginTransaction();
		fragmentTransaction.replace(R.id.content_frame, fragment);
		fragmentTransaction.addToBackStack(null);
		fragmentTransaction.commit();
		distanceSelected = 1;// reset distance dag chon
		invalidateOptionsMenu();
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		FragmentManager fm = getSupportFragmentManager();
		Log.d("---- MainAppActivitygetBackStackEntryCount",
				"" + fm.getBackStackEntryCount());
		if (fm.getBackStackEntryCount() == 1)
			this.finish();
		else {
			Log.d("MainAppActivity", "popping backstack");
			Log.d("MainAppActivity distance seleted:", "" + distanceSelected);
			fm.popBackStackImmediate();
			invalidateOptionsMenu();
		}
	}

	@Override
	public void navigateToLocateDetail(int postion) {
		// TODO Auto-generated method stub
		TAG_FRAGMENT = "LocateDetailFragment";
		LocateDetailsFragment fragment = new LocateDetailsFragment();
		fragment.navigateToLocateDetail(postion);
		FragmentManager fragmentManager = getSupportFragmentManager();
		FragmentTransaction fragmentTransaction = fragmentManager
				.beginTransaction();
		fragmentTransaction.replace(R.id.content_frame, fragment);
		fragmentTransaction.addToBackStack(null);
		fragmentTransaction.commit();
		invalidateOptionsMenu();

	}

	public void navigateToBookMarkRecent() {
		mDrawerLayout.closeDrawers();
		TAG_FRAGMENT = "BookmarkFragment";
		BookmarkRecentFragment fragment = new BookmarkRecentFragment();
		FragmentManager fragmentManager = getSupportFragmentManager();
		FragmentTransaction fragmentTransaction = fragmentManager
				.beginTransaction();
		fragmentTransaction.replace(R.id.content_frame, fragment);
		fragmentTransaction.addToBackStack(null);
		fragmentTransaction.commit();
		invalidateOptionsMenu();
	}

	public void navigateToMyLocate() {
		mDrawerLayout.closeDrawers();
		TAG_FRAGMENT = "MyLocateFragment";
		myLocateFragment = new MyLocateFragment();
		FragmentManager fragmentManager = getSupportFragmentManager();
		FragmentTransaction fragmentTransaction = fragmentManager
				.beginTransaction();
		fragmentTransaction.replace(R.id.content_frame, myLocateFragment);
		fragmentTransaction.addToBackStack(null);
		fragmentTransaction.commit();
		invalidateOptionsMenu();
	}
}
